package com.sinog.auth.config;

import com.sinog.core.util.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @desc 重写DaoAuthenticationProvider验证方法
 * @author lzq
 * @date 2020-05-29 18:32:30
 */
@Slf4j
public class LoginAuthenticationProvider extends DaoAuthenticationProvider {

    private static final BCryptPasswordEncoder BCRYPT_PASSWORD_ENCODER;
    private static final byte[] DECRYPTED = new byte[0];

    static {
        BCRYPT_PASSWORD_ENCODER = new BCryptPasswordEncoder();
    }

    /**
     * 描述
     * @param userDetails userDetails
     * @param authentication authentication
     */
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails,UsernamePasswordAuthenticationToken authentication) {
        if(null == userDetails) {
            throw new UsernameNotFoundException("找不到该用户");
        } else if(null == authentication.getCredentials()) {
            logger.debug("Authentication failedz: no credentials provided");
            throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials","Bad credentials"));
        } else {
            String presentedPassword = authentication.getCredentials().toString();
            log.error("presentedPassword:{}",presentedPassword);
            //前端传递密码解密
            String key = "abcdefghijklmn12";
            String iv = "abcdefghijklmn12";
            //解密
            byte[] decrypted = DECRYPTED;
            try {
                decrypted = AesUtil.aesCbcDecrypt(AesUtil.decryptBase64(presentedPassword),key.getBytes(),iv.getBytes());
                log.error("decrypted:{}",decrypted);
            } catch(Exception e) {
                log.error("发生异常:",e);
            }
            // 单点登录不需要密码，以此为判断！
            if(StringUtils.isNotBlank(presentedPassword)){
                String decode = AesUtil.byteToString(decrypted);
                if(!BCRYPT_PASSWORD_ENCODER.matches(decode,userDetails.getPassword())) {
                    logger.debug("Authentication failed: password does not match stored value");
                    throw new BadCredentialsException("用户名或密码错误");
                }
            }
        }
    }
}